import { Tabs, Popup } from 'antd-mobile'
import { Icon } from '@/components/Icon'

import styles from './index.module.scss'
import { useInitialState } from '@/utils/use-initial-state'
import { getUserChannel } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import Channels from './components/Channels'
import ArticleList from './components/ArticleList'


const Home = () => {
	const dispatch = useDispatch()
	const history = useHistory()

	//拿到切换频道状态
	const { channelActiveKey } = useSelector((state: RootState) => state.home)

	//切换事件
	const onTabChange = (key: string) => {
		dispatch({ type: 'home/changeTab', payload: key })
	}

	useInitialState(getUserChannel, 'home')
	const { userChannel } = useInitialState(getUserChannel, 'home')

	const [visible, setVisible] = useState(false)

  // 频道管理弹出层隐藏
	const onChannelClose = () => {
		setVisible(false)
	}

  // 频道管理弹出层展示
	const onChannelShow = () => {
		setVisible(true)
	}

	return (
		<div className={styles.root}>
			{/* 延迟渲染 Tabs，解决 tab 高亮位置错误 */}
			{userChannel.length > 0 && (
				<Tabs
					className='tabs'
					activeLineMode='fixed'
					activeKey={channelActiveKey}
					onChange={onTabChange}
				>
					{userChannel.map((item) => (
						// forceRender 表示 Tab 在隐藏时也会渲染 DOM 结构
						// 如果希望频道没有选中时，也加载文章列表数据，就设置 forceRender 属性；否则，不设置
						<Tabs.Tab forceRender title={item.name} key={item.id}>
							{/*
                每个频道都有自己的 文章列表 数据，所以，此处将当前频道的 id 传递给 ArticleList 组件
                这样，ArticleList 就可以拿到当前自己频道对应的文章列表数据了
              */}
							<ArticleList channelId={item.id} />
						</Tabs.Tab>
					))}
				</Tabs>
			)}

			<div className='tabs-opration'>
				<Icon
					type='iconbtn_search'
					onClick={() => history.push('/search')}
				/>
				<Icon type='iconbtn_channel' onClick={onChannelShow} />
			</div>

			{/* 频道管理 - 弹出层 */}
			<Popup visible={visible} className='channel-popup' position='left'>
				<Channels onClose={onChannelClose} />
			</Popup>
		</div>
	)
}

export default Home
